import Vue from 'vue'
import { Component } from 'vue-property-decorator'
import { logout } from '@/moduleC/api'
import PageContainer from '@/moduleC/components/layout/PageContainer.vue'
import store from '@/moduleC/store'
import { State } from 'vuex-class'

interface SwitchEvent {
	detail: {
		value: boolean
	}
}

interface UserInfo {
	level: number;
	[key: string]: any;
}

// 添加用户状态接口
interface UserState {
	user: UserInfo | null;
	userToken: string | null;
	is_gray_scale: boolean;
	// ... other state properties
}

@Component({
	components: {
		PageContainer
	},
	name: 'Setting'
})
export default class Setting extends Vue {
	// Data properties
	@State('is_gray_scale') gray!: any
	@State('user') userinfo!: any
	
	switch1Checked = !!(store.state as UserState).is_gray_scale
	
	// 添加空值检查
	get switch1Checked1(): boolean {
		const user = (store.state as UserState).user
		return user ? Number(user.level) === 1 : false
	}

	set switch1Checked1(value: boolean) {
		// 处理设置值的逻辑
	}

	get userInfo(): UserInfo {
		// 添加空值检查
		const user = (store.state as UserState).user
		if (!user) {
			return {
				name: '',
				avatar: '',
				id: '',
				location: '',
				points: 0,
				level: 0,
				coupons: 0
			}
		}
		return user
	}

	// Methods
	goBack(): void {
		uni.navigateBack({
			delta: 1
		})
	}

	switch1Change(e: SwitchEvent): void {
		this.switch1Checked = e.detail.value
		uni.setStorageSync('moduleA_gray_scale', e.detail.value)
		store.dispatch('setStoreData', {
			_key: 'is_gray_scale',
			_val:  e.detail.value
		})
	}

	switch1Change1(e: SwitchEvent): void {
		this.switch1Checked1 = e.detail.value
		const data = {...this.userInfo}
		data.level = Number(e.detail.value)
		uni.setStorageSync('_UserInfo', data)
		store.dispatch('setStoreData', {
			_key: 'user',
			_val: data
		})
	}

	async handleLogout(): Promise<void> {
		try {
			const res = await logout()
			if (res) {
				uni.removeStorageSync('token')
				uni.removeStorageSync('userInfo')
				
				// Navigate to login page
				uni.reLaunch({
					url: '/pages/login/login'
				})
			}
		} catch (error) {
			uni.showToast({
				title: '退出失败，请重试',
				icon: 'none'
			})
		}
	}
}